package com.yunwaikeji.gy_tool_library.utils

import com.google.gson.JsonParseException
import org.apache.http.conn.ConnectTimeoutException
import retrofit2.HttpException
import java.net.ConnectException
import java.net.SocketTimeoutException
import java.net.UnknownHostException

/**
 * 郭杨
 * 2022/11/15 12:04
 */
object GYNetExceptionUtils {
    fun getErrorResult(throwable: Throwable?): String {
        var msg = ""
        throwable.let {
            when (it) {
                is HttpException -> {
                    msg = getHttpResultOfCode(it)
                }
                is ConnectException -> {
                    msg = it.message.toString()
                }
                is ConnectTimeoutException -> {
                    msg = "请求网络超时"
                }
                is UnknownHostException -> {
                    msg = "网络不可用"
                }
                is SocketTimeoutException -> {
                    msg = "请求网络超时"
                }
                is JsonParseException -> {
                    msg = "数据解析错误"
                }
            }
        }
        val errorResult = msg + throwable
        GYLogUtils.printHttpResponse(errorResult)
        return errorResult
    }

    private fun getHttpResultOfCode(httpException: HttpException): String {
        return when {
            httpException.code() == 500 -> {
                "服务器发生错误"
            }
            httpException.code() == 404 -> {
                "请求地址不存在"
            }
            httpException.code() == 403 -> {
                "请求被服务器拒绝"
            }
            httpException.code() == 307 -> {
                "请求被重定向到其他页面"
            }
            httpException.code() == 401 -> {
                "该账号已在其他地方登录, 请重新登录"
            }
            else -> {
                httpException.message()
            }
        }
    }
}